package org.gdstash.character;

import org.gdstash.file.GDReader;
import org.gdstash.file.GDWriter;
import org.gdstash.item.GDAbstractContainer;
import org.gdstash.item.GDItem;
import org.gdstash.util.FileVersionException;
import org.gdstash.util.GDMsgFormatter;

import java.io.IOException;

public class GDCharInventorySack extends GDAbstractContainer {
    private static final int BLOCK = 0;
    private byte tempBool;
    private GDChar gdc;
    private int sackPos;

    public GDCharInventorySack(final GDChar gdc, final int sackPos) {
        super(5);
        this.gdc = gdc;
        this.sackPos = sackPos;
        if (sackPos == 0) {
            this.containerType = 4;
        }
    }

    public void read(final int containerVersion) throws IOException {
        int val = 0;
        final GDReader.Block block = new GDReader.Block();
        val = GDReader.readBlockStart(block);
        if (val != 0) {
            throw new FileVersionException(GDMsgFormatter.getString(GDMsgFormatter.rbMsg, "ERR_UNSUPPORTED_VERSION"));
        }
        this.tempBool = GDReader.readEncByte();
        this.items.clear();
        this.removedItems.clear();
        val = GDReader.readEncInt(true);
        for (int i = 0; i < val; ++i) {
            final GDItem item = new GDItem(this.gdc.getCharName(), this.gdc.isHardcore(), 4);
            item.read(containerVersion);
            if (!item.hasErrors()) {
                this.items.add(item);
            } else {
                this.removedItems.add(item);
            }
        }
        GDReader.readBlockEnd(block);
        this.changed = false;
    }

    public void write(final int containerVersion) throws IOException {
        final GDReader.Block block = new GDReader.Block();
        GDWriter.writeBlockStart(block, 0);
        GDWriter.writeByte(this.tempBool);
        final int val = this.items.size() + this.removedItems.size();
        GDWriter.writeInt(val);
        for (final GDItem item : this.items) {
            item.write(containerVersion);
        }
        for (final GDItem item : this.removedItems) {
            item.write(containerVersion);
        }
        GDWriter.writeBlockEnd(block);
        this.changed = false;
    }

    public int getByteSize(final int containerVersion) {
        int size = 0;
        size += 4;
        size += 4;
        ++size;
        size += 4;
        for (final GDItem item : this.items) {
            size += item.getByteSize(containerVersion);
        }
        for (final GDItem item : this.removedItems) {
            size += item.getByteSize(containerVersion);
        }
        size += 4;
        return size;
    }
}
